package com.sip.stream.utils.zfy;

import android.content.Context;
import android.os.SystemClock;
import android.util.Log;

import com.sip.stream.helper.AudioRecordHelper;
import com.sip.stream.media.ZFYMediaManager;
import com.sip.stream.utils.zfy.callback.ZFYAudioRecordCallBack;
import com.sip.stream.utils.zfy.consumer.IGSMediaObserver;
import com.sip.stream.utils.zfy.consumer.IGSWAVConsumer;

import java.util.List;
import java.util.Vector;

public class GSWAVDataSource extends AudioRecordHelper implements IGSWAVDataSource, ZFYAudioRecordCallBack {
    private static final String TAG = "GSWAVDataSource";
    protected List<IGSWAVConsumer> consumers;
    protected List<IGSMediaObserver<IGSWAVDataSource>> observers;

    public GSWAVDataSource(int i, Context context) {
        super(i, context);
        this.consumers = new Vector();
        this.observers = new Vector();
        this.callBack = this;
    }

    @Override
    public int getSampleRate() {
        return this.sampleRate;
    }

    @Override
    public int getChannelCount() {
        return this.channelCount;
    }

    @Override
    public void onAudioStream(byte[] bArr, long j) {
        for (IGSWAVConsumer iGSWAVConsumer : this.consumers) {
            iGSWAVConsumer.onAudioStream(bArr, j);
        }
    }

    @Override
    public void addConsumer(IGSWAVConsumer iGSWAVConsumer) {
        this.consumers.add(iGSWAVConsumer);
        iGSWAVConsumer.addObserver(this);
        Log.i(TAG, "addConsumer " + iGSWAVConsumer);
        changeMode(ZFYMediaManager.getInstance().getStatus().isRemoteInviteVoiceTalk() ? 1 : 0);
    }

    @Override
    public void addObserver(IGSMediaObserver<IGSWAVDataSource> iGSMediaObserver) {
        this.observers.add(iGSMediaObserver);
    }

    @Override
    public void onError(String str) {
        for (IGSMediaObserver<IGSWAVDataSource> iGSMediaObserver : this.observers) {
            iGSMediaObserver.onStop(this);
        }
    }

    @Override
    public void onAudioStream(byte[] bArr) {
        onAudioStream(bArr, getPresentationTimeUs());
    }

    public long getPresentationTimeUs() {
        return SystemClock.elapsedRealtimeNanos() / 1000;
    }

    @Override
    public void onStop(IGSWAVConsumer iGSWAVConsumer) {
        Log.w(TAG, "onStop " + iGSWAVConsumer);
        this.consumers.remove(iGSWAVConsumer);
        if (this.consumers.isEmpty()) {
            Log.w(TAG, "release");
            for (IGSMediaObserver<IGSWAVDataSource> iGSMediaObserver : this.observers) {
                iGSMediaObserver.onStop(this);
            }
        }
    }
}
